'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Copy, Search, FileText, Code, BookOpen, Calendar, Hash } from 'lucide-react';

export default function QueryPage() {
  const [serialNumber, setSerialNumber] = useState('');
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleQuery = async () => {
    if (!serialNumber.trim()) {
      setError('请输入序列号');
      return;
    }

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      const response = await fetch('/api/query-serial', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ serial_number: serialNumber.trim() })
      });

      const data = await response.json();

      if (data.success) {
        setResult(data.data);
        setSuccess('查询成功！');
      } else {
        setError(data.error || '查询失败');
        setResult(null);
      }
    } catch (error) {
      setError('网络错误：' + (error as Error).message);
      setResult(null);
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setSuccess('内容已复制到剪贴板');
    } catch (error) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      setSuccess('内容已复制到剪贴板');
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      pending: 'secondary',
      summary_generated: 'default',
      completed: 'default'
    } as const;

    const labels = {
      pending: '待生成',
      summary_generated: '已生成摘要',
      completed: '已完成'
    };

    return (
      <Badge variant={variants[status as keyof typeof variants] || 'secondary'}>
        {labels[status as keyof typeof labels] || status}
      </Badge>
    );
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            序列号查询
          </h1>
          <p className="text-gray-600">
            通过序列号查询您生成的软件著作权申请材料
          </p>
        </div>

        {/* 错误和成功消息 */}
        {error && (
          <Alert className="mb-6 border-red-200 bg-red-50">
            <AlertDescription className="text-red-700">
              {error}
            </AlertDescription>
          </Alert>
        )}
        {success && (
          <Alert className="mb-6 border-green-200 bg-green-50">
            <AlertDescription className="text-green-700">
              {success}
            </AlertDescription>
          </Alert>
        )}

        {/* 查询表单 */}
        <Card className="mb-8">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Search className="h-5 w-5" />
              序列号查询
            </CardTitle>
            <CardDescription>
              请输入您要查询的序列号（格式：SWC-XXXXXX-XXXXXX-XXXXXXXX）
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex gap-4">
              <Input
                value={serialNumber}
                onChange={(e) => setSerialNumber(e.target.value)}
                placeholder="请输入序列号"
                className="flex-1"
                onKeyPress={(e) => e.key === 'Enter' && handleQuery()}
              />
              <Button 
                onClick={handleQuery} 
                disabled={loading}
                className="px-8"
              >
                {loading ? '查询中...' : '查询'}
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* 查询结果 */}
        {result && (
          <div className="space-y-6">
            {/* 基本信息 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Hash className="h-5 w-5" />
                  基本信息
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid gap-4 md:grid-cols-2">
                  <div>
                    <p className="text-sm text-gray-600">序列号</p>
                    <div className="flex items-center gap-2 mt-1">
                      <p className="font-mono font-semibold">{result.serial_number}</p>
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => copyToClipboard(result.serial_number)}
                      >
                        <Copy className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  
                  <div>
                    <p className="text-sm text-gray-600">状态</p>
                    <div className="mt-1">
                      {getStatusBadge(result.status)}
                    </div>
                  </div>
                  
                  <div>
                    <p className="text-sm text-gray-600">软件描述</p>
                    <p className="mt-1 font-medium">{result.software_description}</p>
                  </div>
                  
                  <div>
                    <p className="text-sm text-gray-600">开发语言</p>
                    <p className="mt-1 font-medium">{result.development_language}</p>
                  </div>
                  
                  <div>
                    <p className="text-sm text-gray-600">版本号</p>
                    <p className="mt-1 font-medium">{result.version}</p>
                  </div>
                  
                  <div>
                    <p className="text-sm text-gray-600">创建时间</p>
                    <div className="flex items-center gap-2 mt-1">
                      <Calendar className="h-4 w-4 text-gray-500" />
                      <p className="font-medium">{formatDate(result.created_at)}</p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 生成内容 */}
            {(result.application_form_summary || result.code_summary || result.document_summary || 
              result.application_form_full || result.code_full || result.document_full) && (
              <Card>
                <CardHeader>
                  <CardTitle>生成内容</CardTitle>
                </CardHeader>
                <CardContent>
                  <Tabs defaultValue="summary" className="w-full">
                    <TabsList className="grid w-full grid-cols-2">
                      <TabsTrigger value="summary">摘要版本</TabsTrigger>
                      <TabsTrigger value="full" disabled={!result.application_form_full && !result.code_full && !result.document_full}>
                        完整版本
                      </TabsTrigger>
                    </TabsList>
                    
                    <TabsContent value="summary" className="space-y-6">
                      {result.application_form_summary && (
                        <Card>
                          <CardHeader>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <FileText className="h-5 w-5" />
                                <CardTitle className="text-lg">登记申请表摘要</CardTitle>
                              </div>
                              <Button 
                                variant="outline" 
                                size="sm"
                                onClick={() => copyToClipboard(result.application_form_summary)}
                              >
                                <Copy className="h-4 w-4" />
                              </Button>
                            </div>
                          </CardHeader>
                          <CardContent>
                            <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                              {result.application_form_summary}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                      
                      {result.code_summary && (
                        <Card>
                          <CardHeader>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <Code className="h-5 w-5" />
                                <CardTitle className="text-lg">源程序摘要</CardTitle>
                              </div>
                              <Button 
                                variant="outline" 
                                size="sm"
                                onClick={() => copyToClipboard(result.code_summary)}
                              >
                                <Copy className="h-4 w-4" />
                              </Button>
                            </div>
                          </CardHeader>
                          <CardContent>
                            <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                              {result.code_summary}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                      
                      {result.document_summary && (
                        <Card>
                          <CardHeader>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <BookOpen className="h-5 w-5" />
                                <CardTitle className="text-lg">说明文档摘要</CardTitle>
                              </div>
                              <Button 
                                variant="outline" 
                                size="sm"
                                onClick={() => copyToClipboard(result.document_summary)}
                              >
                                <Copy className="h-4 w-4" />
                              </Button>
                            </div>
                          </CardHeader>
                          <CardContent>
                            <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                              {result.document_summary}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </TabsContent>
                    
                    <TabsContent value="full" className="space-y-6">
                      {result.application_form_full && (
                        <Card>
                          <CardHeader>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <FileText className="h-5 w-5" />
                                <CardTitle className="text-lg">登记申请表（完整版）</CardTitle>
                              </div>
                              <Button 
                                variant="outline" 
                                onClick={() => copyToClipboard(result.application_form_full)}
                              >
                                <Copy className="h-4 w-4 mr-2" />
                                复制
                              </Button>
                            </div>
                          </CardHeader>
                          <CardContent>
                            <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                              {result.application_form_full}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                      
                      {result.code_full && (
                        <Card>
                          <CardHeader>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <Code className="h-5 w-5" />
                                <CardTitle className="text-lg">源程序（完整版）</CardTitle>
                              </div>
                              <Button 
                                variant="outline" 
                                onClick={() => copyToClipboard(result.code_full)}
                              >
                                <Copy className="h-4 w-4 mr-2" />
                                复制
                              </Button>
                            </div>
                          </CardHeader>
                          <CardContent>
                            <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                              {result.code_full}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                      
                      {result.document_full && (
                        <Card>
                          <CardHeader>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <BookOpen className="h-5 w-5" />
                                <CardTitle className="text-lg">说明文档（完整版）</CardTitle>
                              </div>
                              <Button 
                                variant="outline" 
                                onClick={() => copyToClipboard(result.document_full)}
                              >
                                <Copy className="h-4 w-4 mr-2" />
                                复制
                              </Button>
                            </div>
                          </CardHeader>
                          <CardContent>
                            <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                              {result.document_full}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </TabsContent>
                  </Tabs>
                </CardContent>
              </Card>
            )}
          </div>
        )}
      </div>
    </div>
  );
}